/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package diet.method;

import diet.dao.DAO;
import diet.dao.DietDAO;
import diet.dao.DietDetailDAO;
import diet.dao.DishDAO;
import diet.dao.UserDAO;
import diet.dto.DietDTO;
import diet.dto.DietDetailDTO;
import diet.dto.DishDTO;
import diet.dto.UserDTO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Vrety
 */
public class ControllerMethod {

    private UserDTO userCreateMenu = null;
    private java.util.Date dt = new java.util.Date();

    public int checkLogin(String username, String password) {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            con = DAO.ConnectWithDriver();
            st = con.createStatement();

            String dtbStr = " SELECT * from [User] WHERE Email = '" + username + "' and Password = '" + password + "'";
            rs = st.executeQuery(dtbStr);
            if (rs.next()) {
                if (rs.getString(10).equals("Admin")) {
                    return 2;
                }
                return 1;
            }
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            return 0;
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException ex) {
                    System.out.println("Connection error: " + ex.getMessage());
                }
            } else if (st != null) {
                try {
                    st.close();
                } catch (SQLException ex) {
                    System.out.println("Statement error " + ex.getMessage());
                }
            } else if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException ex) {
                    System.out.println("ResultSet error " + ex.getMessage());
                }
            }
        }
        return 0;
    }

    public String changeInfo(String customerName, int male, String birthDay, int phone, int height, int weight, String email) {
        Connection con = null;
        PreparedStatement stm = null;
        try {
            con = DAO.ConnectWithDriver();
            stm = con.prepareStatement("Update [User] set CustomerName=?, Male=?, [Birthday]=?, Phone=?, Height=?, [Weight]=? where Email =?");
            stm.setString(1, customerName);
            stm.setInt(2, male);
            stm.setString(3, birthDay);
            stm.setInt(4, phone);
            stm.setInt(5, height);
            stm.setInt(6, weight);
            stm.setString(7, email);
            int i = stm.executeUpdate();
            if (i > 0) {
                return "Changing information successful";
            } else {
                return "Information incorrect";
            }
        } catch (Exception e) {
            return null;
        } finally {
            try {
                stm.close();
                con.close();
            } catch (SQLException ex) {
                Logger.getLogger(ControllerMethod.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public String changePassword(String customerEmail, String currentPassword, String newPass) {
        Connection con = null;
        PreparedStatement stm = null;
        try {
            con = DAO.ConnectWithDriver();
            stm = con.prepareStatement("Update [User] set Password=? where Email =? and Password =?");
            stm.setString(1, newPass);
            stm.setString(2, customerEmail);
            stm.setString(3, currentPassword);
            int i = stm.executeUpdate();
            if (i > 0) {
                return "Changing password successful";
            } else {
                return "Old password incorrect";
            }
        } catch (Exception e) {
            return null;
        } finally {
            try {
                stm.close();
                con.close();
            } catch (SQLException ex) {
                Logger.getLogger(ControllerMethod.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void AutoGenerateMenu(String userName) {
        UserDAO userDao = new UserDAO();
        userCreateMenu = new UserDTO();
        userCreateMenu = userDao.getUserByUsername(userName);
        CreateMenuDefault(userCreateMenu.getUserID());
    }

    //Add to Menu
    public void CreateMenuDefault(int userID) {

        DietDTO diet = new DietDTO();
        diet.setDietName("Default");
        diet.setIsNew(1);
        //set datetime now

        diet.setDateTimeBegin(dt);

        // + 7 day, not search
        //java.sql.Date sqlDate = new java.sql.Date(dt.getTime());
        Calendar c = Calendar.getInstance();
        c.setTime(dt);
        c.add(Calendar.DATE, 7);
        dt = c.getTime();
        diet.setDateTimeEnd(dt);

        diet.setCustomerID(userID);
        //Calculator Calories
        int age = 20;
        if (userCreateMenu.getBirthday() != null) {
            //age = dt. userCreateMenu.getBirthday();
        }
        if (userCreateMenu.getMale() == 0) {
            Double calory = userCreateMenu.getWeight() * 9.99 + userCreateMenu.getHeight() * 6.25 - age * 4.92 + 5;
            if (calory != null) {
                diet.setCalorieNeed(calory.intValue());
            }
        } else {
            Double calory = userCreateMenu.getWeight() * 9.99 + userCreateMenu.getHeight() * 6.25 - age * 4.92 - 161;
            if (calory != null) {
                diet.setCalorieNeed(calory.intValue());
            }
        }
        DietDAO dietDao = new DietDAO();
        //Insert
        dietDao.add(diet);

        CreateDietDetail(dietDao.getNewestDiet());

    }

    //Add to DietDetail
    public void CreateDietDetail(DietDTO diet) {
        //Create for 7 day
        int i = 0;
        while (i < 7) {

            for (Iterator<DishDTO> it1 = RandomFood(diet.getCalorieNeed()).iterator(); it1.hasNext();) {
                //Set params
                DishDTO dishDTO = it1.next();
                DietDetailDTO dietDetail = new DietDetailDTO();
                dietDetail.setDietID(diet.getDietID());
                dietDetail.setDishID(dishDTO.getDishID());
                dietDetail.setTime(dishDTO.getTime());
                Calendar c = Calendar.getInstance();
                Date dts = new Date();
                c.setTime(dts);
                c.add(Calendar.DATE, i);
                dts = c.getTime();
                dietDetail.setDateTime(dts);
                //Add DietDetail
                DietDetailDAO dao = new DietDetailDAO();
                //Insert
                dao.add(dietDetail);
            }
            i++;
        }
    }

    public List<DishDTO> RandomFood(int totalCalories) {
        List<DishDTO> list = new ArrayList<DishDTO>();
        int num = 0;
        int calories = 0;
        Random r = new Random();
        DishDAO dishDao = new DishDAO();
        while (calories < totalCalories) {
            //Add morning
            if (num == 0) {
                List<DishDTO> listrandom = new ArrayList<DishDTO>();
                listrandom = dishDao.getListDishByTime("morning");
                int index = r.nextInt(listrandom.size() - 1);
                //set morning this dish to menu
                listrandom.get(index).setTime("morning");
                list.add(listrandom.get(index));
                calories += listrandom.get(index).getCalories();
            } else if (num >= 2 && num <= 4) {
                List<DishDTO> listrandom = new ArrayList<DishDTO>();
                listrandom = dishDao.getListDishByTime("noon");
                int index = r.nextInt(listrandom.size() - 1);
                //set morning this dish to menu
                listrandom.get(index).setTime("noon");
                list.add(listrandom.get(index));
                calories += listrandom.get(index).getCalories();
            } else {
                List<DishDTO> listrandom = new ArrayList<DishDTO>();
                listrandom = dishDao.getListDishByTime("evening");
                int index = r.nextInt(listrandom.size() - 1);
                //set morning this dish to menu
                listrandom.get(index).setTime("evening");
                list.add(listrandom.get(index));
                calories += listrandom.get(index).getCalories();
            }
            num++;
        }
        return list;
    }
}
